import { useEffect, useState } from 'react'

function initCookie() {
  const result = {}
  const cookie = document.cookie
  cookie.split('; ').forEach((item) => {
    const [key, value] = item.split('=')
    return (result[key] = decodeURIComponent(value))
  })
  return result
}

export const useCookie = () => {
  const [cookies, setCookies] = useState(initCookie)

  useEffect(() => {
    setCookies(initCookie())
  }, [])

  return {
    has: (name) => {
      return Reflect.has(cookies, name)
    },
    get: (name) => {
      return Reflect.get(cookies, name, null)
    },
  }
}
